package com.easy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easy.bean.Product;
import com.easy.bean.ProductImage;
import com.easy.common.CommonResult;
import com.easy.dao.IImageDao;
import com.easy.dao.IProductDao;
import com.easy.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Primary
public class ProductImpl implements IProductService {
    @Autowired
    IProductDao iProductDao;
    @Autowired
    IImageDao iImageDao;

    // 将id的图片表中的image更新到商品表中的image
    @Override
    public CommonResult updateImage(Integer id) {
        QueryWrapper<ProductImage> imageWrapper = new QueryWrapper<>();
        imageWrapper.eq("id",id);
        ProductImage image = iImageDao.selectOne(imageWrapper);
        if (image == null) {
            return CommonResult.fail("没有找到该商品的 sort=1 的图片");
        }
        Product product = iProductDao.selectById(image.getProductId());
        product.setImage(image.getImage());
        int result = iProductDao.updateById(product);
        if (result > 0) {
            return CommonResult.success("成功更新了商品的图片");
        } else {
            return CommonResult.fail("没有商品图片被更新");
        }
    }

    @Override
    public CommonResult updateImage() {
        QueryWrapper<ProductImage> imageWrapper = new QueryWrapper<>();
        imageWrapper.eq("sort",1);
        List<ProductImage> imageList = iImageDao.selectList(imageWrapper);

        // 检查是否有符合条件的图片
        if (imageList == null || imageList.isEmpty()) {
            return CommonResult.fail("没有找到任何 sort=1 的商品图片");
        }

        int result =0;
        for(ProductImage img:imageList){
            Product product = iProductDao.selectById(img.getProductId());
            if(product != null){
                product.setImage(img.getImage());
                int count = iProductDao.updateById(product);
                if(count>0){
                    result++;
                }
            }
        }
        if (result > 0) {
            return CommonResult.success("成功更新了 " + result + " 条商品的图片");
        } else {
            return CommonResult.fail("没有商品图片被更新");
        }
    }
}
